package com.shopping.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.shopping.bean.ShopCar;
import com.shopping.bean.User;
import com.shopping.service.GoodsService;
import com.shopping.service.ShopCarService;
import com.shopping.service.UserService;
import com.shopping.service.impl.GoodsServiceImpl;
import com.shopping.service.impl.ShopCarServiceImpl;
import com.shopping.service.impl.UserServiceImpl;

@WebServlet("/addGoodsGoShopCar.do")
public class AddGoodsOnShopCar extends HttpServlet{

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		GoodsService gs = new GoodsServiceImpl();
		UserService us = new UserServiceImpl();
		int goodsId = Integer.parseInt(req.getParameter("gId"));
		User user = (User) req.getSession().getAttribute("loginUser");
		ObjectMapper om = new ObjectMapper();
		String str = "添加失败";
		if(user == null) {
			resp.setCharacterEncoding("UTF-8"); //设置 后端给前端传回的编码格式为utf-8
			resp.setContentType("application/json");// 后端告知前端 返回的数据 是 json格式(不是html /css)
			resp.getWriter().print(om.writeValueAsString(str));
		}else {
			int userId = us.getUserId(user.getUserName(), user.getPassWord());
			ShopCarService scs = new ShopCarServiceImpl();
			ShopCar sc = scs.selectShopCarGoods(goodsId,userId);
			int goodsNum;
			if(sc == null) {
				goodsNum = 1;
				str = gs.insertGoodsGoShopCar(userId,goodsId,goodsNum);
				resp.setCharacterEncoding("UTF-8"); //设置 后端给前端传回的编码格式为utf-8
				resp.setContentType("application/json");// 后端告知前端 返回的数据 是 json格式(不是html /css)
				resp.getWriter().print(om.writeValueAsString(str));
			}else {
				goodsNum = sc.getGoodsNum();
				str = gs.insertGoodsGoShopCar(userId,goodsId,goodsNum++);
				resp.setCharacterEncoding("UTF-8"); //设置 后端给前端传回的编码格式为utf-8
				resp.setContentType("application/json");// 后端告知前端 返回的数据 是 json格式(不是html /css)
				resp.getWriter().print(om.writeValueAsString(str));
			}
		}
		
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doGet(req,resp);
	}
	

}
